package org.acghub.mtdb.test;

import java.util.concurrent.*;

public class AsyncOperation {
    static final ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(10);
    // 略去线程池定义
    public CompletableFuture<String> doGet() {
        return CompletableFuture.supplyAsync(() -> {
            // do sth
            System.out.println("parent");
            return "parent";
        }, EXECUTOR_SERVICE).thenComposeAsync(parentResult -> {
            // 子任务
            return CompletableFuture.supplyAsync(() -> {
                System.out.println("child");
                return "child";
            }, EXECUTOR_SERVICE);
        }, EXECUTOR_SERVICE).thenApplyAsync(x -> {
            // ...
            System.out.println("end");
            return "end";
        }, EXECUTOR_SERVICE);
    }

    public static void main(String[] args) {
        AsyncOperation operation = new AsyncOperation();
        CompletableFuture<String> future = operation.doGet();
        // ...
        String result = future.orTimeout(200, TimeUnit.MILLISECONDS)
                .join();
        // ...

        EXECUTOR_SERVICE.shutdown();
    }
}
